package main

import (
	"fmt"
	"strconv"
)

type Node struct {
	val int
	name string
	next *Node
}

func(n *Node) String() string {
	return strconv.Itoa(n.val)+","+n.name
}

type CircleLinkedList struct {
	head Node
}

//向循环单链表插入节点
func (cl *CircleLinkedList) insertToList (node *Node) {
	if cl.head.next == nil {
		cl.head.next = node
		node.next = node
	}else {
		temp := cl.head.next
		for temp.next != cl.head.next {
			//继续往后遍历
			temp = temp.next
		}
		//将node插入到temp的后面
		node.next = temp.next
		temp.next = node
	}
}

//从循环单链表删除节点
func (cl *CircleLinkedList) deleteFromList (value int) {
	if cl.head.next == nil {
		fmt.Println("链表为空")
	}else {
		temp := cl.head.next
		if temp.val == value {
			//要删除头结点指向的下一个节点
			//先判断是否只有一个节点
			if temp.next == temp {
				cl.head.next = nil
			}else {
				//cl.head.next = temp.next
				tempNode := *temp
				for temp.next != cl.head.next {  //先遍历找到最后一个节点
					temp = temp.next
				}
				cl.head.next = tempNode.next
				temp.next = temp.next.next
			}
		}else {
			for temp.next != cl.head.next && temp.next.val != value{
				//继续往后遍历
				temp = temp.next
			}
			if temp.next == cl.head.next {
				fmt.Println("未找到该节点")
			}else {
				//temp的下一个节点是要删除的节点
				temp.next = temp.next.next
			}
		}
	}
}

//遍历循环单链表
func (cl *CircleLinkedList) showList () {
	if cl.head.next == nil {
		fmt.Println("链表为空")
	}else {
		temp := cl.head.next
		fmt.Println(temp)
		for temp.next != cl.head.next {
			//继续往后遍历
			temp = temp.next
			fmt.Println(temp)
		}
	}
}

func main() {
	headNode := Node{}
	cl := CircleLinkedList{
		head:headNode,
	}

	n1 := Node{
		val:  1,
		name: "tom",
		next: nil,
	}

	n2 := Node{
		val:  2,
		name: "jack",
		next: nil,
	}

	n3 := Node{
		val:  3,
		name: "scott",
		next: nil,
	}
	cl.showList()
	cl.insertToList(&n1)
	cl.showList()
	cl.insertToList(&n2)
	cl.showList()
	cl.insertToList(&n3)
	cl.showList()

	cl.deleteFromList(1)
	cl.showList()
	cl.deleteFromList(2)
	cl.showList()
	cl.deleteFromList(4)
	cl.showList()
}
